<?php

namespace app\index\controller;

use app\admin\service\OssService;
use app\BaseController;
use app\index\model\SystemModel;
use app\index\model\Version as VersionModel;
use app\index\validate\LoginValidate;
use email\Email;

class System extends BaseController
{
    public function getVersion()
    {
        $params = $this->request->post(['version']);
        $sql = new VersionModel();
        $info = $sql->order('create_at', 'desc')->findOrEmpty();
        if ($info->isEmpty()) {
            return result()->fail("暂无版本", 500);
        }
        if($info['versionCode'] > $params['version']) {
            $oss = new OssService();
            $info['downloadUrl'] = $oss->signId($info['fileId']);
            return result()->success($info);
        }
        return result()->fail("已是最新版本", 500);
    }
    public function emailSms()
    {
        $params = $this->request->post(['email', 'type']);
        $validate = new LoginValidate();
        if (!$validate->scene('sms')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $code = rand_number(6);
        $emailInfo = new Email($params['email']);
        $emailInfo->setTitle("验证码");
        $emailInfo->setBody("您的验证码是：".$code);
        if(!$emailInfo->send()) {
            return result()->fail("验证码发送失败", 500);
        }
        $cacheKey = $params['email'].$params['type'];
        cache($cacheKey, $code, 60);
        return result()->success("验证码已发送到您的邮箱");
    }

    public function getText()
    {
        $sql = new SystemModel();
        $params = $this->request->get(['key']);
        $info = $sql->where('key', $params['key'])->findOrEmpty();
        return result()->success($info);
    }

    public function upload()
    {
        $files = request()->file();
        try {
            validate(['file' => [
                'fileSize' => 20 * 1024 * 1024,
                'fileExt' => 'gif,jpg,png'
            ]])->check(['file' => $files]);
            $savename = [];
            foreach ($files as $file) {
                $savename[] = URL . UPLOADIMAGE . str_replace("\\", "/", \think\facade\Filesystem::disk('public')->putFile('img', $file));
            }
            return result()->success($savename);
        } catch (\think\exception\ValidateException $e) {
            result()->fail("上传失败", 500);
        }
    }
}
